import { ref, shallowRef, VNode } from "vue"
import Contextmenu from "../component/contextmenu.vue";
import Main from "../main";

export default (main: Main) => {

    const enabled = ref(true);

    // const loading = ref(false);
    const visible = ref(false);
    const vnode = shallowRef<VNode>()
    const posStyle = ref('');
    //
    let localPos = {x:0,y:0} ;
    let graphPos = {x:0,y:0};
    //
    const offset = 10;
    let w: any = 0;
    let h: any = 0;
    let wd: any = 0;
    let hd: any = 0;
    // mounted 方法
    main.graph.onMounted(() => {
        // 添加移除方法
        main.graph.rootEl.addEventListener('click',() => {
            close();
        })
    })

    // 坐标值计算
    const getLocalPos = (e?:MouseEvent) => {
        if(e){
            localPos = main.graph.pageToLocal(e.pageX, e.pageY)
        }
        return localPos;
        
    }

    const getGraphPos = (e?:MouseEvent) => {
        if(e){
            graphPos = main.graph.localToGraph(getLocalPos(e))
        }
        return graphPos;
    }

    const calcStyle = (e:MouseEvent) => {
        if (!main.graph.isInit) return;
        const el = main.graph.boxEl;
        w = el?.offsetWidth;
        h = el?.offsetHeight;
        wd = w / 3;
        hd = h / 3 + h / 6;
        // 获取坐标
        const {x,y} = getGraphPos(e)
        // 判断坐标位置 计算 菜单的位置
        let l = false;
        let t = false;
        if (w - x < wd) {
            l = true;
        }
        if (h - y < hd) {
            t = true;
        }
        // 生成当前的 坐标样式
        posStyle.value = `${l ? 'right' : 'left'}:${(l ? w - x : x) + offset}px;${t ? 'bottom' : 'top'}:${t ? h - y : y}px;`
        //
        // console.log('....',posStyle.value)
    }
    //
    const open = async (event:any,node?:VNode) => {
        if(!node){
            close();
            return;
        }
        calcStyle(event)
        // 变更鼠标指针到 loading 
        // loading.value = true;
        //
        if(!visible.value){
            visible.value = true;
            vnode.value = node;
        }
        else{
            vnode.value = undefined;
            setTimeout(() => {
                vnode.value = node;
            },100)
        }
    }
    //
    const close = () => {
        visible.value = false;
        vnode.value = undefined;
        posStyle.value = '';
    }

    return {
        enabled,
        Contextmenu,
        //
        props:{visible,posStyle,vnode,close},
        //
        open,
        close,
        getLocalPos,
        getGraphPos

    }
}